﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;

namespace ExaminationSys.Helper
{
    public class FormsAuthenticationHelper
    {
        private static readonly TeacherInfoService Proxy = ObjectFactory<TeacherInfoService>.Create();
        private static readonly StudentService ProxyStudent = ObjectFactory<StudentService>.Create();
        public static void Logout()
        {
            var formsAuth = new FormsAuthenticationHelper.FormsAuthenticationService();
            formsAuth.SignOut();
          // HttpContext.Current.Response.Redirect("~/Account/Login.aspx");
        }

        public static int UpdatePassword(string newPwd)
        {
            var item = GetCurrentTeacherInfo();
            if (item == null) return -1;

            item.PWD = DESHelper.Encrypt(newPwd);
            int retCode = 0;
            var flag = Proxy.Update(item);
            if (flag)
            {
                HttpContext.Current.Session["TeacherInfo"] = item;
                retCode = 1;
            }
            return retCode;
        }

        public static int CheckPwd(string pwd)
        {
            var item = GetCurrentTeacherInfo();
            if (item == null)
            {
                return -1;
            }
            pwd = DESHelper.Encrypt(pwd);
            return pwd.Equals(item.PWD) ? 1 : 0;
        }

        private static void ResetStudentSession()
        {
            var loginInfo = HttpContext.Current.Session["StudentInfo"];
            if (loginInfo == null)
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies["SJEDU_UID"];
                if (cookie != null)
                {
                    var uid = cookie["UID"];
                    var pwd = cookie["PWD"];

                    var student = Proxy.Login(uid, pwd);
                    if (student == null)
                    {
                        HttpContext.Current.Response.Redirect("Index.aspx");
                    }
                    else
                    {
                        HttpContext.Current.Session["StudentInfo"] = student;
                    }
                }
                else
                {
                    HttpContext.Current.Response.Redirect("Index.aspx");
                }
            }
        }

        public static int CheckStudentPwd(string pwd)
        {
            ResetStudentSession();
            var loginInfo = HttpContext.Current.Session["StudentInfo"] as Student;
            if (loginInfo == null)
            {
                return -1;
            }
            pwd = DESHelper.Encrypt(pwd);
            return pwd.Equals(loginInfo.PWD) ? 1 : 0;
        }

        public static int UpdateStudentPwd(string newPwd)
        {
            ResetStudentSession();
            var item = HttpContext.Current.Session["StudentInfo"] as Student;
            if (item == null) return -1;

            item.PWD = DESHelper.Encrypt(newPwd);
            int retCode = 0;
            var flag = ProxyStudent.Update(item);
            if (flag)
            {
                HttpContext.Current.Session["StudentInfo"] = item;
                retCode = 1;
            }
            return retCode;
        }

        public interface IFormsAuthentication
        {
            void SignIn(string userName, bool createPersistentCookie);
            void SignOut();
        }
        public static long Login(string email, string password)
        {
            //email = email.SqlSafe();
            //password = password.SqlSafe();
            var hashPwd = DESHelper.Encrypt(password);
            var item = Proxy.Login(email, hashPwd);
            var result = 0;
            if(item!=null)
            {
                SetTeacherCookie(email, password);
                HttpContext.Current.Session["TeacherInfo"] = item;
            }
            else
            {
                result = -1;
            }
            return result;
        }

        private static  void SetTeacherCookie(string uid, string pwd)
        {
            if (HttpContext.Current != null)
            {


                HttpCookie cookie = HttpContext.Current.Request.Cookies["SJEDU_Teacher"];
                if (cookie == null)
                {
                    cookie = new HttpCookie("SJEDU_Teacher");
                }
                var hashpwd = DESHelper.Encrypt(pwd);
                cookie.Values.Set("UID", uid);
                cookie.Values.Set("PWD", hashpwd);
                cookie.Expires = DateTime.Today.AddDays(7);
                HttpContext.Current.Response.SetCookie(cookie);
            }
        }

        public static void RemoveTeacherCookie()
        {
            if (HttpContext.Current != null)
            {

                var cookie = HttpContext.Current.Request.Cookies["SJEDU_Teacher"];
                cookie.Expires = DateTime.Today.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }

        public static TeacherInfo GetCurrentTeacherInfo()
        {
            var obj = HttpContext.Current.Session["TeacherInfo"] as TeacherInfo;
            if(obj==null)
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies["SJEDU_Teacher"];
                if (cookie != null)
                {
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        //还原身份
                        var uid = cookie["UID"];
                        var pwd = cookie["PWD"];
                        obj = Proxy.Login(uid, pwd);
                        if (obj != null) HttpContext.Current.Session["TeacherInfo"] = obj;

                    }
                    else
                    {
                        RemoveTeacherCookie();
                    }
                }
            }
            return obj;
        }

        public static string GetCurrentUserID()
        {
            var item = GetCurrentTeacherInfo();
            return item == null ? "" : item.UserID;
        }

    


        public static void SignOut()
        {
            FormsAuthentication.SignOut();
        }
        public class FormsAuthenticationService : IFormsAuthentication
        {
            public void SignIn(string userName, bool createPersistentCookie)
            {
                FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
            }
            public void SignOut()
            {
                FormsAuthentication.SignOut();
            }
        }

        public interface IMembershipService
        {
            int MinPasswordLength { get; }

            bool ValidateUser(string userName, string password);
            MembershipCreateStatus CreateUser(string userName, string password, string email);
            bool ChangePassword(string userName, string oldPassword, string newPassword);
        }

        public class AccountMembershipService : IMembershipService
        {
            private MembershipProvider provider;

            public AccountMembershipService() : this(null) { }

            public AccountMembershipService(MembershipProvider provider)
            {
                this.provider = this.provider ?? Membership.Provider;
            }

            public int MinPasswordLength
            {
                get
                {
                    return this.provider.MinRequiredPasswordLength;
                }
            }

            public bool ValidateUser(string userName, string password)
            {
                return (userName.Equals("demo") && password.Equals("demo"));
                //return this.provider.ValidateUser(userName, password);
            }

            public MembershipCreateStatus CreateUser(string userName, string password, string email)
            {
                MembershipCreateStatus status;
                this.provider.CreateUser(userName, password, email, null, null, true, null, out status);
                return status;
            }

            public bool ChangePassword(string userName, string oldPassword, string newPassword)
            {
                MembershipUser currentUser = this.provider.GetUser(userName, true /* userIsOnline */);
                return currentUser.ChangePassword(oldPassword, newPassword);
            }
        }
    }
}